#include <SDL/SDL_image.h>
#include <SDL/SDL_ttf.h>
#include "Gomoku.h"
#include "MainWindow.h"
#include "PushButton.h"
#include "ButtonManager.h"
#include "PlayerTurnPrompter.h"
#include "ThreadManager.h"
#include "SinglePlayerScreen.h"

SinglePlayerScreen::SinglePlayerScreen()
	: GameScreen(), m_ia(&Gomoku::Instance().getPlayers()[1])
{
}

SinglePlayerScreen::~SinglePlayerScreen()
{
}

static int playIA(void* _datas)
{
	IA* ia = (IA*)_datas;
	
	ia->doEvents();
	if (Gomoku::Instance().CurrentPlayer->EnnemyPiecesCount >= 10)
		Gomoku::Instance().Arbiter.SetCurrentPlayerWin(true);
	if (Gomoku::Instance().Arbiter.HasCurrentPlayerWon() == false)
		Gomoku::Instance().nextPlayerTurn();
	return (0);
}

void SinglePlayerScreen::doEvents()
{	
	if (PlayerTurnPrompter::Instance().Count == 0)
	{
		if (ButtonManager::Instance().update() == false)
			return ;
		for (int i = 0; i < 2; i++)
		{
			if (Gomoku::Instance().getPlayers()[i].Winner == true)
			{
				PlayerTurnPrompter::Instance().setText("Game reinitialized", COLOR_BLACK);
				PlayerTurnPrompter::Instance().Count = 50;
				Gomoku::Instance().reset();
				return ;
			}
		}
		if (Gomoku::Instance().CurrentPlayer->Winner == false)
		{
			if (Gomoku::Instance().CurrentPlayer->Color == COLOR_BLACK)
			{
				this->setBlockOnButtons(false);
				m_board.setCanRemove(true);
				m_board.setCanMovePieces(m_checkBoxMovePieces->isChecked());
				m_board.setCanRemovePieces(m_checkBoxCanRemovePiece->isChecked());
				m_board.doEvents();
				m_currentPlayer = NULL;
				if (Gomoku::Instance().Arbiter.RuleThree() == true)
					m_currentInfos = INFOS_RULE_THREE;
				else
					m_currentInfos = INFOS_WAITING;
			}
			else
			{
				if (Gomoku::Instance().CurrentPlayer != m_currentPlayer)
				{
					this->setBlockOnButtons(true);
					m_board.setCanRemove(false);
					m_currentPlayer = Gomoku::Instance().CurrentPlayer;
					Gomoku::Instance().Threads->useThread(playIA, (void*)&m_ia);
					m_currentInfos = INFOS_AI;
					//playIA((void*)&m_ia);
				}
				Gomoku& gomoku = Gomoku::Instance();
				if (gomoku.Arbiter.HasCurrentPlayerWon() == true)
				{
					gomoku.CurrentPlayer->Winner = true;
					gomoku.Arbiter.SetCurrentPlayerWin(false);
				}
				/*else
				{
					PlayerTurnPrompter::Instance().setText("IA is thinking...", COLOR_BLACK);
				}*/
			}
		}
	}

	this->GameScreen::doEvents();
}
